<template>
  <view>
    <view class="upload">
      <uv-upload @afterRead="selectPhotos"
                 @delete="deletePhotos"
                 @oversize="photosOver"
                 :fileList="uploads"
                 :maxSize="10485760"
                 accept="image"
                 :maxCount="upload_max" multiple :previewFullImage="true"></uv-upload>
    </view>
  </view>
</template>

<script>

import {
  HTTP_REQUEST_URL,
  HEADER
} from '@/config/app';
import store from '@/store';
import * as InfraUtil from '@/api/infra.js';

export default {
  name: "UvUpload",
  props: {
    types: {
      type: String,
      default: 'image'
    },
    img: {
      type: Object,
      default: function () {
        return {
          width: '60rpx',
          height: '60rpx',
        }
      }
    },
    // 给的参数;原路返回
    params: {
      type: Object,
      default: function () {
        return {}
      }
    },
    dataList: {
      type: Array,
      default: function () {
        return []
      }
    },
    //上传图片大小 默认3M
    upload_max: {
      type: Number,
      default: 3
    }
  },
  data() {
    return {
      uploads: [],
    }
  },
  watch: {
    dataList: {
      handler(newList, o) {
        console.log("回显图片:", newList)
        let arr = [];
        for (let i = 0; i < newList.length; i++) {
          let item = newList[i];
          if (item !== undefined && item !== null) {
            arr.push({
              status: 'success',
              message: '',
              name: '',
              url: item
            });
            // this.uploads.push({
            //   status: 'success',
            //   message: '',
            //   name: '',
            //   url: item
            // })
          }
        }
        this.uploads = arr;
      }
    }
  },
  methods: {
    // 选择上传图片
    async selectPhotos(e) {
      console.log("选择图片", e);
      let files = e.file;
      let length = this.uploads.length;
      for (let i = 0; i < files.length; i++) {
        // 上传图片
        let item = files[i];
        this.uploads.push({
          ...files[i],
          status: 'uploading',
          message: '上传中',
          name: item.name
        });
        let res = await this.upload(item);
        this.uploads.splice(length, 1, Object.assign(item, {
          status: 'success',
          message: '',
          name: item.name,
          url: res.data.url
        }));
        ++length;
      }
      this.$emit('uploadChange', {
        "params": this.params,
        "images": this.uploads
      });
    },

    deletePhotos(e) {
      this.uploads.splice(e.index, 1);
      this.$emit('uploadChange', {
        "params": this.params,
        "images": this.uploads
      });
    },

    upload(item) {
      let header = {...HEADER, 'Authorization': store.state.app.token};
      delete header['content-type'];
      let that = this;
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: HTTP_REQUEST_URL + '/file/upload',
          header: header,
          filePath: item.url,
          formData: {
            name: item.name
          },
          name: 'file',
          success: (res) => {
            if (res.statusCode === 200) {
              let data = JSON.parse(res.data);
              if (data.code === 200) {
                setTimeout(() => {
                  resolve(data)
                }, 100)
              }
            }else {
              that.uploads.pop()
            }
          }
        });
      })
    },

    // 图片超出大小限制
    photosOver(file, lists, name) {
      this.$refs.notify.show({
        message: '单张图片最大限制10MB',
        type: 'warning',
        duration: 1000,
        safeAreaInsetTop: true
      });
    },
  },
  created() {
    for (let i = 0; i < this.dataList.length; i++) {
      let item = this.dataList[i];
      if (item !== undefined && item !== null) {
        this.uploads.push({
          status: 'success',
          message: '',
          name: '',
          url: item
        })
      }
    }
  }
}
</script>

<style scoped>
</style>
